package com.sinan.core.connector;

import lombok.EqualsAndHashCode;
import lombok.Getter;

/**
 * 属性校验结果
 * 线程安全，属性不可更改
 * @author pengpei
 */
@EqualsAndHashCode
@Getter
public final class ValidationResult {

    private final String subject;

    /**
     * this input value that was tested for validity
     */
    private final String input;

    /**
     * an explanation of the validation result
     */
    private final String explanation;

    /**
     * true if current result is valid; false otherwise
     */
    private final boolean valid;

    private ValidationResult(final Builder builder) {
        this.subject = builder.subject;
        this.input = builder.input;
        this.explanation = builder.explanation;
        this.valid = builder.valid;
    }

    public static Builder builder() {
        return new Builder();
    }

    @Override
    public String toString() {
        if (input == null) {
            return String.format("'%s' is %s because %s", subject, valid ? "valid" : "invalid", explanation);
        } else {
            return String.format("'%s' validated against '%s' is %s because %s", subject, input, valid ? "valid" : "invalid", explanation);
        }
    }


    public static final class Builder {

        private String subject;

        private String input = "";

        private String explanation = "";

        private boolean valid = false;


        /**
         * 默认为false
         * @param valid 代表校验是否有效，true 代表有效，false 代表无效
         * @return builder
         */
        public Builder valid(final boolean valid) {
            this.valid = valid;
            return this;
        }


        /**
         *
         * @param input 待校验的值
         * @return builder
         */
        public Builder input(final String input) {
            if (null != input) {
                this.input = input;
            }
            return this;
        }

        /**
         * 默认为空字符串
         *
         * @param explanation 检验结果
         * @return builder
         */
        public Builder explanation(final String explanation) {
            if (null != explanation) {
                this.explanation = explanation;
            }
            return this;
        }

        /**
         * @param subject 被检验的对象
         * @return builder
         */
        public Builder subject(String subject) {
            if (null != subject) {
                this.subject = subject;
            }
            return this;
        }

        public ValidationResult build() {
            return new ValidationResult(this);
        }
    }
}
